<template>
  <div>
    <el-row>
      <el-select v-model="type" style="font-size: 10px;margin-right: 20px;" @change="typeChange">
        <el-option label="全部" value="all"></el-option>
        <el-option label="用户" value="user"></el-option>
        <el-option label="管理员" value="admin"></el-option>
      </el-select>
      <el-input v-model.trim="user_name" placeholder="请输入名称查询" prefix-icon="el-icon-search"
        style="width:250px"></el-input>
      <el-button type="primary" plain @click="searchUser">搜索</el-button>
      <el-button type="info" plain icon="el-icon-circle-plus" @click="showAddUser"
        style="margin-left: 30px;">新增用户</el-button>
    </el-row>
    <el-table :data="tableData" height="730" border style="width: 100%;margin-top: 10px;font-size: 16px;">
      <el-table-column prop="user_name" label="姓名">
      </el-table-column>
      <el-table-column prop="user_role" label="用户类型">
        <template slot-scope="scope">
          <el-tag :type="scope.row.user_role === 0 ? 'primary' : 'success'" disable-transitions>{{ scope.row.user_role ===
            0
            ? '用户' : '管理员' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="300">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="medium" icon="el-icon-edit-outline" @click="handleEdit(scope.$index, scope.row)">
          </el-button>
          <el-button slot="reference" size="medium" type="danger" plain icon="el-icon-delete-solid"
            @click="handleDelete(scope.$index, scope.row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top:20px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page_num"
        :page-sizes="[4, 8, 12, 16]" :page-size="page_size" layout="total, sizes, prev, pager, next, jumper"
        :total="total_size">
      </el-pagination>
    </div>

    <el-dialog title="更新用户信息" width="30%" :modal-append-to-body=false :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="ruleForm">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model.trim="form.userName" autocomplete="off" disabled maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" maxlength="15">
          <el-input v-model.trim="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" maxlength="20">
          <el-input v-model.trim="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-select v-model="form.type" placeholder="">
            <el-option label="管理员" value='1'></el-option>
            <el-option label="用户" value='0'></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancel"> 取 消</el-button>
        <el-button type="primary" @click="dialogOK">更 新</el-button>
      </div>
    </el-dialog>

    <!-- 新增用户 -->

    <el-dialog :visible.sync="addUserDialogVisible" :modal-append-to-body=false width="50%" title="新增用户">
      <el-form :model="addForm" ref="addForm" :rules="rules" label-width="240px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" autocomplete="off" style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" autocomplete="off" style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" autocomplete="off" style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="普通用户" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off" show-password
            style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="addForm.checkPass" autocomplete="off" show-password
            style="width:50%"></el-input>
        </el-form-item>
        <el-form-item size="large" style="margin-top: 30px;">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser" :loading="submitLoading">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import adminapi from "@/api/admin.js"
import loginApi from "@/api/login.js"
export default {


  data() {
    return {
      addUserDialogVisible: false,
      addForm: {
        username: '',
        phone: '',
        email: '',
        type: '0',
        password: '',
        checkPass: ''
      },

      user_name: '',
      type: 'user',
      tableData: [],
      total_size: 10,
      page_num: 1,
      page_size: 12,
      dialogFormVisible: false,
      formLabelWidth: '70px',
      form: {
        userName: '',
        phone: '',
        email: '',
        type: '0'
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }, { min: 3, max: 20, message: '用户名长度需为5-20个字符', trigger: 'blur' }, { validator: this.validateName, trigger: 'blur' }],
        phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, { min: 8, max: 20, message: '手机号长度需为5-20个字符', trigger: 'blur' }, { validator: this.validateNumber, message: '请输入数字', trigger: 'blur' }],
        email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
        type: [{ required: true, message: '用户类型不能为空', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }, { min: 6, max: 20, message: '密码长度需为5-20个字符', trigger: 'blur' }],
        checkPass: [{ required: true, message: '请再次输入密码', trigger: 'blur' }, { validator: this.checkPassword, trigger: 'blur' }]
      },
      submitLoading: false,

    }
  },
  methods: {
    showAddUser() {
      this.addForm = this.$options.data().addForm
      this.addUserDialogVisible = true;
    },
    validateName(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        // 发请求，判断用户名是否存在
        loginApi.nameExist(this.addForm.username).then(res => {
          let sign = res.data.sign; // 返回false, 表示用户名已存在; 返回true, 表示用户名不存在
          if (sign) {
            callback();
          } else {
            callback(new Error("用户名已被注册"));
          }
        });
      }
    },
    //新增用户
    addUser() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          adminapi.addUser(this.addForm.username, this.addForm.phone, this.addForm.email, this.addForm.type, this.addForm.password)
            .then(res => {
              if (res.data.msg === 1) {
                this.submitLoading = false
                this.addUserDialogVisible = false
                this.$message.success('新增用户成功');
                this.loadUserInfo();
              } else {
                this.$message.error('添加用户失败')
              }
            }).catch(error => {
              console.log(error);
            })

        }
      })
    },

    validateNumber(rule, value, callback) {
      if (value === '' || isNaN(value)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    },

    //确认密码
    checkPassword(rule, value, callback) {
      if (value !== this.addForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    //获取用户信息
    async loadUserInfo() {
      const res = await adminapi.loadUser(this.type, this.user_name, this.page_num, this.page_size)
      if (res.data.total) {
        this.total_size = res.data.total;
        this.tableData = res.data.userinfo;
      } else {
        this.tableData = [];
      }

    },
    //类型改变Ch
    typeChange(val) {
      this.loadUserInfo();
    },
    //搜索
    searchUser() {
      this.loadUserInfo();
    },

    // 表格操作
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.form.userName = row.user_name;
      this.form.type = String(row.user_role);
      this.form.phone = row.phone;
      this.form.email = row.email;
    },
    //删除
    handleDelete(index, row) {
      this.$confirm('是否确定删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminapi.deleteUser(row.user_id).then(res => {
          if (res.data.msg === 1) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.loadUserInfo();
          } else {
            this.$message.error("删除失败")
          }
        }).catch(error => {
          console.log(error);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //page_size 改变
    handleSizeChange(val) {
      this.page_size = val;
      this.loadUserInfo();
    },
    //翻页
    handleCurrentChange(val) {
      this.page_num = val;
      this.loadUserInfo();
    },
    dialogCancel() {
      this.dialogFormVisible = false;
    },
    async dialogOK() {
      adminapi.updateUser(this.form.userName, this.form.phone, this.form.email, this.form.type).
        then(async res => {
          if (res.data.msg === 1 && res.data.count > 0) {
            await this.loadUserInfo();
            this.$message({
              message: '更新成功',
              type: 'success'
            });
          } else {
            this.$message({
              message: '更新失败',
              type: 'error'
            })
          }
        }).catch(error => {
          console.log(error);
        })
      this.dialogFormVisible = false;
      await this.loadUserInfo();
    },

  },

  mounted() {
    this.loadUserInfo();
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__body-wrapper {
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #1296db;
    height: 6px;
    border-radius: 8px;
  }
}
</style>